import className from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import { Backdrop } from '../backdrop';
import { Icon } from '../icon';

export interface IModalProps {
  visible?: boolean;
  children?: React.ReactNode;
  className?: string;
  showBackdrop?: boolean;
  onBackdropClick?: any;
  style?: React.CSSProperties;
}

export interface IModalHeaderProps {
  children?: React.ReactNode;
  className?: string;
  style?: React.CSSProperties;
  onClose?: () => void;
}

export interface IModalContentProps {
  children?: React.ReactNode;
  className?: string;
  style?: React.CSSProperties;
}

export interface IModalFooterProps {
  children?: React.ReactNode;
  className?: string;
  style?: React.CSSProperties;
}

const Header = (props: IModalHeaderProps) => {
  return (
    <div className={className('br-modal__header', props.className)} style={props.style}>
      <div className="br-modal__header--title">
        {props.children}
      </div>
      <Icon className="br-modal__close-icon" type="close" onClick={props.onClose} />
    </div>
  );
};

const Content = (props: IModalContentProps) => {
  return (
    <div className={className('br-modal__content', props.className)} style={props.style}>
      {props.children}
    </div>
  );
};

const Footer = (props: IModalFooterProps) => {
  return (
    <div className={className('br-modal__footer', props.className)} style={props.style}>
      {props.children}
    </div>
  );
};

export class Modal extends React.Component<IModalProps> {
  public static Header = Header;
  public static Content = Content;
  public static Footer = Footer;

  public static propTypes = {
    style: PropTypes.object,
    onClose: PropTypes.func,
    visible: PropTypes.bool,
    children: PropTypes.node,
    className: PropTypes.string,
    showBackdrop: PropTypes.bool,
    onBackdropClick: PropTypes.func,
  };

  public ele: Element;

  constructor(props: IModalProps) {
    super(props);
    this.ele = document.createElement('div');
  }

  public componentDidMount() {
    document.body.appendChild(this.ele);
  }

  public componentWillUnmount() {
    document.body.removeChild(this.ele);
  }

  public render() {
    const styleObj = this.props.style ? this.props.style : {};
    if (!this.props.visible) {
      styleObj.display = 'none';
    }

    const modalBox = <div style={styleObj} className="br-modal">
      {this.props.children}
    </div>;

    return ReactDOM.createPortal(
      this.props.showBackdrop ?
        <Backdrop visible={this.props.visible} children={modalBox} onBackdropClick={this.props.onBackdropClick} />
        : modalBox,
      this.ele,
    );
  }
}
